package org.urchr.beorganized.api.impl.xml;

import java.io.StringWriter;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletResponse;

import org.urchr.beorganized.api.base.PrivateBaseAPIServlet;
import org.urchr.beorganized.dao.NotesDAO;
import org.urchr.beorganized.dao.XMLDocumentBuilder;
import org.urchr.beorganized.dao.errors.GeneralException;
import org.urchr.beorganized.dao.tables.Note;

public class XMLExport extends PrivateBaseAPIServlet {

	public XMLExport() {
		// TODO Auto-generated constructor stub
		skipBody = true;
	}
	
	@Override
	protected void doProcessPrivate() throws GeneralException {
		Note note = NotesDAO.getNote(NotesDAO.safeInt(getParameter("noteid"), -1), userID);
		if(note!=null){
			try {
				response.setContentType("application/octet-stream");
				response.addHeader("Content-Disposition", "attachment; filename=export_"+note.getId()+".zip");
				ZipOutputStream zip = new ZipOutputStream(response.getOutputStream());
//				BufferedOutputStream out = new BufferedOutputStream(zip);
				StringWriter writer = new StringWriter();
				if(XMLDocumentBuilder.writeXML(new XMLExportReader(note, zip, servletContext), writer, true)){
					zip.putNextEntry(new ZipEntry("contents.xml"));
					zip.write(writer.getBuffer().toString().getBytes("utf-8"));
					zip.close();
					return;
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
		}
		response.setStatus(HttpServletResponse.SC_NOT_FOUND);
	}

}
